<template>
  <div class="goods">
  	  <div class="menu-wrapper" ref="menuWrapper">
  	  	<ul>
  	  		<li v-for="(item,index) in goods" 
  	  			class="menu-item"
  	  			:class="{'current':currentIndex === index}"
  	  			@click="selectMenu(index,$event)"
  	  		>
  	  			<span class="text border-1px">
  	  				<span v-show="item.type>0" 
  	  					class="icon"
						:class="classMap[item.type]"
  	  				></span>
  	  				{{item.name}}
  	  			</span>
  	  		</li>
  	  	</ul>
  	  </div>
  	  <div class="foods-wrapper" ref="foodsWrapper">
  	  	<ul>
  	  		<li v-for="item in goods" class="food-list food-list-hook">
  	  			<h1 class="title">{{item.name}}</h1>
  	  			<ul>
  	  				<li @click="selectFood(food,$event)" v-for="food in item.foods" class="food-item border-1px">
  	  					<div class="icon"><img :src="food.icon" width="57" height="57"></div>
						<div class="content">
							<h2 class="name">{{food.name}}</h2>
							<p class="desc">{{food.description}}</p>
							<div class="extra">
								<span class="count">月售{{food.sellCount}}</span><span>好评率{{food.rating}}%</span>
							</div>
							<div class="price">
								<span class="now">￥{{food.price}}</span><span v-show="food.oldPrice" class="old">￥{{food.oldPrice}}</span>
							</div>
							<div class="carcontrol-wrapper">
                                <!-- 加减按钮 -->
								<cartcontrol :food="food" @increment="incrementTotal"></cartcontrol>
							</div>							
						</div> 	  			
  	  				</li>
  	  			</ul>
  	  		</li>
  	  	</ul>
  	  </div>
      <!-- 购物车（抛物线小球） -->
  	   <shop-cart :select-foods="selectFoods" :delivery-price="seller.deliveryPrice"
  	   			   :min-price="seller.minPrice" ref="shopcart"
  	   >   	
  	   </shop-cart>

      <!-- 详情页 -->
      <food  @add="addFood"  :food="selectedFood" ref="food"></food>


  </div>
</template>

<script>

import BScroll from 'better-scroll'
import ShopCart from "../shoppingcart/shoppingcart.vue"
import cartcontrol from "../cartcontrol/cartcontrol.vue"
import food from "../food/food"

const ERR_OK = 0;

export default {
  name: 'GOODS',
  props:{
  	seller:Object
  },
  components:{
  	ShopCart,
  	cartcontrol,
    food
  },
  data(){
  	return {
  		goods:[],
  		listHeight:[],
  		scrollY:0,
      selectedFood: {}
  	}
  },
  created(){
  	this.classMap = ['decrease','discount',"special",'invoice','guarantee']	

  	  var url='/api/goods.json'
  		this.$http.get(url).then(res => { 
  			//console.log(res)
  			 res = res.body
  			if(res.errno === ERR_OK){

  				this.goods = res.data	
  				this.$nextTick(() => {  //可以用 $nextTick 來确保Dom变化后再执行一些事情
		         	this._initScroll();
		         	this._calculateHeight();
		      });
				//this._initScroll()
				//this._calculateHeight()			
  				//console.log(this.goods)
  			}
		  }, error => {
		 		 console.log('goods请求失败')
		  });
  },
  computed:{
  	currentIndex(){ //计算到达哪个区域的区间的时候的对应的索引值
  		for(let i = 0;i < this.listHeight.length;i++){
  			let height1 = this.listHeight[i]//当前menu子块的高度
  			let height2 = this.listHeight[i + 1]//下一个menu子块的高度
  			//!height 解决 i遍历到最后一个值时i++
  			//滚动到底部的时候,height2为undefined,需要考虑这种情况
            //需要确定是在两个menu子块的高度区间
  			if (!height2 || (this.scrollY >= height1 && this.scrollY < height2)){
  				return i
  			}
  		}
  		//神魔都没有返回0
  		return 0
  	},
  	selectFoods(){
  		let foods = [];
  		this.goods.forEach( (good) => {
  			good.foods.forEach((food) => {
  				if(food.count){
  					//count存在时的{}对象存入数组，数据中包含price
  					foods.push(food)
  				}
  			})
  		})

  		return foods
  	}
  },
   methods:{
   		_initScroll(){
   			this.menuScroll = new BScroll(this.$refs.menuWrapper,{
   				click:true//结合BScroll的接口使用,是否将click事件传递,默认被拦截了
   			})
   			this.foodsScroll = new BScroll(this.$refs.foodsWrapper,{
   				probeType:3,
   				click:true//结合BScroll的接口使用,是否将click事件传递,默认被拦截了
   			})
   			//结合BScroll的接口使用,3实时派发scroll事件，探针的作用
			//将滚动式告诉滚动的位置
			
			//结合BScroll的接口使用,监听scroll事件(实时派发的),并获取鼠标坐标，当滚动时能实时暴露出scroll
   			this.foodsScroll.on('scroll',(pos)=>{
   				this.scrollY = Math.abs(Math.round(pos.y))
   				//console.log(this.scrollY)  				
   			})
   		},
   		_calculateHeight(){
   			let foodList = this.$refs.foodsWrapper.getElementsByClassName('food-list-hook')//获取每一个food的dom对象
   			//console.log(foodList)
   			let height = 0
   			this.listHeight.push(height)//初始化第一个高度为0
   			for(let i=0;i< foodList.length;i++){
   			    //每一个item都是刚才获取的food的每一个dom
   				let item = foodList[i]
   				//主要是为了获取每一个foods内部块的高度
   				//第一个循环i=0时listHeight[0]中传入的第一个height初始化为0的值
   				//变为了foodList[0].clientHeight(也为0)
   				//console.log(this.listHeight)
   				height += item.clientHeight
   				//console.log(this.listHeight)
   				this.listHeight.push(height)//每个food-list-hook的位置
   			}
   			//console.log(this.listHeight)
   		},
   		selectMenu (index,event){//better-scroll会阻止掉click事件，需要在初始化时，开启click	
   			//解决pc点击触发两次click事件问题（better-scroll的，浏览器原生的）
   			//去掉自带的click事件点击，即pc端直接返回 
   			//_constructed浏览器原生没有这个属性
   			if(!event._constructed){
   				return
   			}
   			//console.log(index)
   			let foodList =  this.$refs.foodsWrapper.getElementsByClassName('food-list-hook')
   			let el = foodList[index]
   			//类似jump to的功能,通过这个方法,跳转到指定的dom
   			this.foodsScroll.scrollToElement(el,300)
   		},
   		incrementTotal(target){
   			//点击小球时有点卡,可采用异步执行的方式回调
   			this._drop(target);
   		},
        addFood(target) {
            this._drop(target);
        },
        _drop(target) {
            // 体验优化，异步执行下落动画
            this.$nextTick(() => {
              this.$refs.shopcart.drop(target);
            });
        },
        selectFood(food, event) {
            if (!event._constructed) {
              return;
            }
            this.selectedFood = food;
            this.$refs.food.show();
        }
  },
}
</script>
<style lang="stylus" rel="stylesheet/stylus" scoped >
@import '../../common/stylus/mixin.styl'
.goods
	display:flex
	position:absolute
	top:174px
	bottom:46px
	width:100%
	overflow:hidden
	//左固定，右自适应
	.menu-wrapper
		flex:0 0 80px
		width:80px
		background:#f3f5f7
		.menu-item
			display:table
			width:56px
			height:54px
			line-height:14px
			padding:0 12px
			&.current
				position relative
				z-index 10
				margin-top:-1px
				background:#fff
				font-weight 700
				.text
					border-none()			
			.text
				display:table-cell
				vertical-align:middle
				width:56px
				border-1px(rgba(1, 17, 27, .2))
				font-size:12px	 		
				.icon
					display:inline-block
					vertical-align:top
					width:12px
					height:12px
					margin-right:2px
					background-size:12px 12px
					background-repeat:no-repeat
					&.decrease
						bg-image("decrease_3")
					&.discount
						bg-image("discount_3")
					&.guarantee
						bg-image('guarantee_3')
					&.invoice
						bg-image('invoice_3')
					&.special
						bg-image('special_3')								
	.foods-wrapper
		flex:1
		.title
			padding-left 14px
			height:26px
			line-height 26px
			border-left:2px solid #d9dde1
			font-size 12px
			color:rgb(147,153,159)
			background:#f3f5f7 
		.food-item
			display flex
			margin:18px
			border-1px(rgba(1, 17, 27, .2))
			padding-bottom:18px
			&:last-child
				border-none()
				margin-bottom:0
			.icon
				flex:0 0 57px
				margin-right 10px
			.content
				flex:1
				.name
					font-size 14px
					margin:2px 0 8px
					height:14px
					line-height 14px
					color:rgb(7,17, 27)
				.desc,.extra
					line-height 10px
					font-size 10px
					color rgb(147,153,159)
				.desc
					margin-bottom 8px
					line-height 12px
				.extra
					.count
						margin-right:12px
				.price
					font-weight 700
					line-height 24px
					.now
						margin-right 9px
						font-size 14px
						color rgb(240,20,20)
					.old
						text-decoration: line-through
						font-size 10px
						color rgb(147,153,159)
				.carcontrol-wrapper
					position:absolute
					right:0
					bottom:12px
						
					
					
			
</style>
